// fetchData.js
import { routes6 } from './config.js';

function getSelectedPlatform() {
    const selected = document.querySelector('input[name="platform"]:checked');
    return selected ? selected.value : null;
}

function fetchData(routeKey, objData = null) {
    // const platform = getSelectedPlatform();
    let endpoint = routes6[routeKey];
    // if (platform === "douyin") {
    //     endpoint = routes4[routeKey];
    // }
    // else if (platform === "ttxm") {
    //     endpoint = routes5[routeKey];
    // }

    if (!endpoint) {
        console.error('Invalid route key:', routeKey);
        return;
    }

    let url = endpoint + "?t=" + Date.now();
    if (objData !== null) {
        url += `&${objData.key}=${objData.value}`;
    }
    console.log('url:', url);
    fetch(url)
        .then(response => response.json())
        .then(data => {
            // 获取数据展示区域
            const dataList = document.getElementById('data-list');
            // 清空当前列表
            dataList.innerHTML = '';
            let res = data.res;
            let querytime = data.time;
            let token = data.token;

            // 创建一个段落来显示 res 和 querytime
            const resQueryInfo = document.createElement('p');
            resQueryInfo.textContent = `Response: ${res}, token: ${token}, Query Time: ${querytime}`;
            dataList.appendChild(resQueryInfo);

            // 检查数据结构并逐条展示
            if (data.data) {
                // 创建表格
                const table = document.createElement('table');
                table.style.width = '100%';
                table.style.borderCollapse = 'collapse';

                // 创建表头
                const thead = document.createElement('thead');
                const headerRow = document.createElement('tr');
                const headers = ['openId', 'activeTime', 'hadSubscribe', 'holdRewardCooling', 'firstLoginTime'];
                headers.forEach(headerText => {
                    const th = document.createElement('th');
                    th.textContent = headerText;
                    th.style.border = '1px solid #ddd';
                    th.style.padding = '8px';
                    th.style.textAlign = 'left';
                    headerRow.appendChild(th);
                });
                thead.appendChild(headerRow);
                table.appendChild(thead);

                // 创建表体
                const tbody = document.createElement('tbody');
                for (const openId in data.data) {
                    if (data.data.hasOwnProperty(openId)) {
                        const userData = data.data[openId];
                        const row = document.createElement('tr');
                        headers.forEach(header => {
                            const td = document.createElement('td');
                            let textcontent = "";
                            if (header == "activeTime" || header == "holdRewardCooling" || header == "firstLoginTime") {
                                let datestr = new Date(userData[header]).toLocaleString();
                                textcontent = datestr;
                            }
                            else {
                                textcontent = userData[header] !== undefined ? userData[header] : 'N/A';
                            }
                            td.textContent = textcontent;
                            td.style.border = '1px solid #ddd';
                            td.style.padding = '8px';
                            row.appendChild(td);
                        });
                        tbody.appendChild(row);
                    }
                }
                table.appendChild(tbody);

                // 将表格添加到数据列表中
                dataList.appendChild(table);
            } else {
                if (routeKey == "querySession") {
                    const li = document.createElement('li');
                    li.textContent = 'No data available';
                    dataList.appendChild(li);
                }
            }
        })
        .catch(error => {
            console.error('Error fetching data:', error);
            const li = document.createElement('li');
            li.textContent = 'Error fetching data';
            dataList.appendChild(li);
        });
}


// 显示输入框和确定按钮；type=1，活跃天数；type=2，重置玩家
function showInputForQueryActive(routeKey, type = 1) {
    const dataList = document.getElementById('data-list');
    dataList.innerHTML = '';

    // 创建输入框容器
    const inputContainer = document.createElement('div');
    inputContainer.className = 'input-container';

    // 创建输入框
    const input = document.createElement('input');
    if (type == 1) {
        input.type = 'number';
        input.placeholder = '输入天数';
    }
    else {
        input.type = 'text';
        input.placeholder = '输入openId';
    }

    // 创建确定按钮
    const confirmButton = document.createElement('button');
    confirmButton.textContent = '确定';

    // 绑定确定按钮点击事件
    confirmButton.addEventListener('click', () => {
        let objData;
        if (type == 1) {
            const days = parseInt(input.value, 10);
            if (!isNaN(days) && days > 0) {
                objData = { "key": "day", "value": days }
                fetchData(routeKey, objData);
            } else {
                alert('请输入有效的天数');
            }
        }
        else {
            let userId = input.value;
            if (userId != "") {
                objData = { "key": "userId", "value": userId }
                fetchData(routeKey, objData);
            }
        }
    });

    // 将输入框和按钮添加到容器中
    inputContainer.appendChild(input);
    inputContainer.appendChild(confirmButton);

    // 将容器添加到数据列表中
    dataList.appendChild(inputContainer);
}

function queryLog(routeKey) {
    const dataList = document.getElementById('data-list');
    dataList.innerHTML = '';

    // 创建日期选择容器
    const dateContainer = document.createElement('div');
    dateContainer.className = 'date-container';

    // 创建日期选择组件
    const dateInput = document.createElement('input');
    dateInput.type = 'date';

    // 创建确定按钮
    const confirmButton = document.createElement('button');
    confirmButton.textContent = '确定';

    // 绑定确定按钮点击事件
    confirmButton.addEventListener('click', () => {
        const selectedDate = dateInput.value;
        if (selectedDate) {
            // 将日期转换为所需的格式（例如：YYYY-MM-DD）
            fetchStreamData(routeKey, selectedDate);
        } else {
            alert('请选择一个日期');
        }
    });

    // 将日期选择组件和按钮添加到容器中
    dateContainer.appendChild(dateInput);
    dateContainer.appendChild(confirmButton);

    // 将容器添加到数据列表中
    dataList.appendChild(dateContainer);
}

/**
 * 查询流数据
 * @param {*} routeKey 
 * @param {*} logtime 
 * @returns 
 */
function fetchStreamData(routeKey, logtime) {
    // const platform = getSelectedPlatform();
    let endpoint = routes6[routeKey];
    // if (platform === "douyin") {
    //     endpoint = routes4[routeKey];
    // }
    // else if (platform === "ttxm") {
    //     endpoint = routes5[routeKey];
    // }
    if (!endpoint) {
        console.error('Invalid route key:', routeKey);
        return;
    }

    let url = endpoint + "?t=" + Date.now();
    if (logtime !== null) {
        url += `&day=${logtime}`;
    }
    fetch(url)
        .then(response => response.json())
        .then(data => {
            // 获取数据展示区域
            const dataList = document.getElementById('data-list');
            // 清空当前列表
            dataList.innerHTML = '';
            let res = data.res;
            let querytime = data.time;
            let streamstr = data.data;
            // 创建一个段落来显示 res 和 querytime
            const resQueryInfo = document.createElement('p');
            resQueryInfo.textContent = `Response: ${res}, Query Time: ${querytime}`;
            dataList.appendChild(resQueryInfo);

            const resQueryInfo2 = document.createElement('p');
            resQueryInfo2.textContent = streamstr;
            dataList.appendChild(resQueryInfo2);
        });
}

/**
 * 修改游戏配置
 * @param {*} routeKey 
 */
function modifyGameConfig(AppPackage) {
    // 1，读取配置信息，GameConfig.json的地址是 https://apidemo6.ckbuyu.com/static/GameConfig.json
    let configUrl = routes6['root'];
    if (!AppPackage)
        configUrl += 'static/GameConfig.json?t=' + Date.now();
    else
        configUrl += 'static/' + AppPackage + '/GameConfig.json?t=' + Date.now();

    fetch(configUrl)
        .then(response => response.json())
        .then(data => {
            const dataList = document.getElementById('data-list');
            dataList.innerHTML = ''; // 清空当前内容

            // 展示原始配置信息
            const configDisplay = document.createElement('pre');
            configDisplay.textContent = JSON.stringify(data, null, 2);
            configDisplay.style.backgroundColor = '#f4f4f4';
            configDisplay.style.padding = '10px';
            configDisplay.style.overflowX = 'auto';
            dataList.appendChild(configDisplay);

            // 2，显示输入框和确定按钮
            const label1 = document.createElement('label');
            label1.textContent = 'ECPM: ';
            label1.style.display = 'block';
            label1.style.marginTop = '10px';
            const input1 = document.createElement('input');
            input1.type = 'number';
            input1.style.display = 'block';
            input1.style.marginTop = '5px';
            input1.value = data.ecpm;

            const label2 = document.createElement('label');
            label2.textContent = 'IPU: ';
            label2.style.display = 'block';
            label2.style.marginTop = '10px';
            const input2 = document.createElement('input');
            input2.type = 'number';
            input2.style.display = 'block';
            input2.style.marginTop = '5px';
            input2.value = data.ipu;

            const saveButton = document.createElement('button');
            saveButton.textContent = '确定';
            saveButton.style.marginTop = '10px';

            saveButton.addEventListener('click', () => {
                try {
                    let updatedConfig = data;
                    updatedConfig.ecpm = parseInt(input1.value);
                    updatedConfig.ipu = parseInt(input2.value);

                    // 3，保存配置信息（模拟 POST 请求）
                    saveUpdatedConfig(updatedConfig).then(() => {
                        const successMsg = document.createElement('p');
                        successMsg.textContent = '配置已成功保存！';
                        successMsg.style.color = 'green';
                        dataList.appendChild(successMsg);

                        configDisplay.textContent = JSON.stringify(updatedConfig, null, 2);
                    }).catch(error => {
                        const errorMsg = document.createElement('p');
                        errorMsg.textContent = '保存失败，请重试。';
                        errorMsg.style.color = 'red';
                        dataList.appendChild(errorMsg);
                        console.error('保存配置出错:', error);
                    });
                } catch (e) {
                    alert('请输入有效的 JSON 格式！');
                }
            });

            dataList.appendChild(label1);
            dataList.appendChild(input1);
            dataList.appendChild(label2);
            dataList.appendChild(input2);
            dataList.appendChild(saveButton);
        })
        .catch(error => {
            console.error('获取配置失败:', error);
            const errorMsg = document.createElement('p');
            errorMsg.textContent = '无法加载配置，请检查网络连接或稍后再试。';
            errorMsg.style.color = 'red';
            document.getElementById('data-list').appendChild(errorMsg);
        });
}
/**
 * 模拟保存更新后的配置
 * @param {*} configData 
 * @returns {Promise<void>}
 */
function saveUpdatedConfig(configData) {
    return new Promise((resolve, reject) => {
        let saveUrl = routes6['saveGameConfig'];

        fetch(saveUrl, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(configData)
        })
            .then(response => {
                if (!response.ok) {
                    throw new Error('Network response was not ok');
                }
                return response.json();
            })
            .then(result => {
                console.log('保存结果:', result);
                resolve();
            })
            .catch(error => {
                reject(error);
            });
    });
}



export { fetchData, showInputForQueryActive, queryLog, fetchStreamData, modifyGameConfig };